<template>
	<div style="display: flex; align-items: center; gap: 4px;">
		<el-input v-model="weight" style="flex: 1;" clearable :class="inputClass">
			<template slot="append">Kg</template>
		</el-input>

		<!-- 连接电子称 -->
		<el-tooltip
			class="item"
			effect="light"
			:content="$tt('label_auto_weight_connect_digital')"
			placement="top-start"
		>
			<i
				v-if="!connected"
				@click="dialogFormVisible = true"
				class="el-icon-connection"
				style="font-size: 16px; color:#333;  cursor: pointer; margin-left: 10px; "
			></i>
		</el-tooltip>

		<!-- 已连接 -->
		<el-popover
			v-if="connected"
			placement="top"
			width="auto"
			trigger="hover"
			v-model="popoverVisible"
		>
			<div style="text-align: center; ">
				<!-- 电子称已连接 -->
				<div style="font-size: 14px; color: #278000; margin-top: 10px; ">
					{{ $tt('label_auto_weight_has_connected') }}
				</div>
				<div>
					<!-- 断开连接 -->
					<el-button type="text" icon="el-icon-close" @click="disconnect">
						{{ $tt('label_auto_weight_disconnect') }}
					</el-button>
				</div>
			</div>
			<i
				slot="reference"
				class="el-icon-connection"
				style="font-size: 16px;  color: #1bc013; font-weight: bold; cursor: pointer; margin-left: 10px; "
			></i>
		</el-popover>

		<el-dialog
			:title="$tt('label_auto_weight_connect_digital')"
			:visible.sync="dialogFormVisible"
			width="540px"
			append-to-body
		>
			<div
				style="display: flex; gap: 8px; margin-top: 20px; margin-bottom: 20px; padding-right: 20px; align-items: center;"
			>
				<!-- 电子称型号 -->
				<div style="padding-left: 20px;">{{ $tt('label_auto_weight_digital_type') }}</div>
				<el-select v-model="type" :placeholder="$tt('tip_please_select')" style="flex: 1;">
					<el-option
						v-for="item in options"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					>
					</el-option>
				</el-select>
			</div>
			<div style="margin-top: 20px; text-align: right; padding-right: 20px;">
				<!-- 确定连接 -->
				<el-button type="primary" @click="startConnect(false)" icon="el-icon-connection">
					{{ $tt('label_auto_weight_sure_connect') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
// ----------------------------------------------------
// --------- 其他型号的电子称，以类似方法新增 js 类 ---------
// ----------------------------------------------------

// cas db1/h 型号电子称

// cas db1/h 型号电子称
import CAS_DB1_H from './protocol/CAS_DB1_H.js'
import ZCS_R_3 from './protocol/ZCS_R_3.js'
import CHS_D_R from './protocol/CHS_D_R.js'

import Vue from 'vue'

export default {
	name: 'auto_weight',

	components: { CAS_DB1_H, ZCS_R_3, CHS_D_R },

	data() {
		return {
			options: [
				{ label: '[CAS] DB1,DB1H', value: 'CAS_DB1_H' },
				{ label: 'ZCS+R-3', value: 'ZCS_R_3' },
				{ label: 'CHS-D+R', value: 'CHS_D_R' }
			],
			type: '',
			connected: false,
			serialObj: null,
			form: {},
			dialogFormVisible: false,
			popoverVisible: false,
			inputClass: 'none-shanshuo',

			weight: '',
			instanceId: 'ato_' + this.$uuid()
		}
	},

	props: {
		value: null
	},

	created() {
		let _this = this
		_this.type = _this.options[0].value

		Vue.prototype.$autoWeightGlobal.autoWeightObjects[_this.instanceId] = _this

		if (Vue.prototype.$autoWeightGlobal.status == 'connected') {
			_this.updateConnectStatus(true)
			return
		}

		// 刷新浏览器后的自动连接处理
		let lastConnect = window.localStorage.getItem('auto_weight_type')
		if (lastConnect && lastConnect != '') {
			_this.type = lastConnect
			_this.startConnect(true)
		}
	},

	destroyed() {
		let _this = this
		delete Vue.prototype.$autoWeightGlobal.autoWeightObjects[_this.instanceId]
	},

	watch: {
		weight(val, old) {
			this.$emit('input', val)
			this.inputClass = 'shanshuo'
			window.setTimeout(() => {
				this.inputClass = 'none-shanshuo'
			}, 500)
		},
		value(val, old) {
			this.weight = val
		}
	},
	methods: {
		startConnect(autoConnect) {
			let _this = this
			if (this.$reg.IP(window.location.hostname)) {
        console.log("hostname is ip")
			} else if (!window.location.protocol.startsWith('https')) {
				this.$message({
					type: 'error',
					message: this.$t('label_auto_weight_only_https') // '您的浏览器不支持串口连接'
				})
				return
			}

			// 其他型号的电子称，以类似方法新增 js 类

			let serialObj = Vue.prototype.$autoWeightGlobal.serialObj
			if (serialObj) {
				return
			}

			// cas db1/h 型号
			if (this.type == 'CAS_DB1_H') {
				serialObj = CAS_DB1_H
			} else if (this.type == 'ZCS_R_3') {
				serialObj = ZCS_R_3
			} else if (this.type == 'CHS_D_R') {
				serialObj = CHS_D_R
			} else {
				alert('error type: ' + this.type)
			}

			Vue.prototype.$autoWeightGlobal.serialObj = serialObj

			let lastV = '-1'
			let lastTime = new Date().getTime()
			let stableValue = -1
			let stableHasSended = false

			serialObj.connectSerial({
				// 是否自动连接
				autoConnect: autoConnect,
				// 连接成功后的回调
				connected: () => {
					console.log('connected')

					_this.dialogFormVisible = false
					_this.popoverVisible = false

					// 更新连接状态
					Vue.prototype.$autoWeightGlobal.status = 'connected'
					let autoWeightObjects = Vue.prototype.$autoWeightGlobal.autoWeightObjects
					for (let atKey in autoWeightObjects) {
						autoWeightObjects[atKey].updateConnectStatus(true)
					}
				},
				connectFail: () => {
					delete Vue.prototype.$autoWeightGlobal.serialObj
					Vue.prototype.$autoWeightGlobal.status = 'init'
				},
				// 电子称数值监听
				monitor: v => {
					// 稳定值处理
					if (v != lastV) {
						lastV = v
						lastTime = new Date().getTime()
						stableValue = -1
						stableHasSended = false
					} else {
						// 超过1.5s 不变触发 stableValue 事件
						if (new Date().getTime() - lastTime >= 1000) {
							stableValue = v
						}
					}

					_this.weight = v
					Vue.prototype.$autoWeightGlobal.value = v

					let stableValueFlaot = parseFloat(stableValue)
					let autoWeightObjects = Vue.prototype.$autoWeightGlobal.autoWeightObjects
					for (let atKey in autoWeightObjects) {
						autoWeightObjects[atKey].updateWeight(v) //.$emit('input', v)
						if (!stableHasSended && stableValueFlaot > 0) {
							autoWeightObjects[atKey].$emit('stableValue', stableValue)
						}
					}
					if (!stableHasSended && stableValueFlaot > 0) {
						stableValue = -1
						stableHasSended = true
					}
				}
			})
		},

		disconnect() {
			let _this = this

			let serialObj = Vue.prototype.$autoWeightGlobal.serialObj
			if (serialObj) {
				try {
					serialObj.close()
				} catch (e) {
					console.log(e)
				}
			}

			// delte serial obj
			delete Vue.prototype.$autoWeightGlobal.serialObj

			// clean connect status
			Vue.prototype.$autoWeightGlobal.status = 'init'
			let autoWeightObjects = Vue.prototype.$autoWeightGlobal.autoWeightObjects
			for (let atKey in autoWeightObjects) {
				autoWeightObjects[atKey].updateConnectStatus(false)
			}

			console.log('disconnect')
		},

		updateWeight(newWeight) {
			this.weight = newWeight
		},
		updateConnectStatus(connected) {
			this.connected = connected
		}
	}
}
</script>

<style>
.shanshuo input {
	animation: shimmer 0.2s infinite;
}
.none-shanshuo input {
	animation: none;
}
@keyframes shimmer {
	0% {
		color: #ffffff;
	}
	50% {
		color: #606266;
	}
	100% {
		color: #ffffff;
	}
}
</style>
